import os
import subprocess

class VideoSplitter:
    """将视频平均切成两段"""

    def __init__(self, input_folder, output_folder):
        self.input_folder = input_folder
        self.output_folder = output_folder
        os.makedirs(self.output_folder, exist_ok=True)
        self.supported_exts = ('.mp4', '.mkv', '.avi', '.mov', '.flv', '.ts')

    def get_duration(self, video_path):
        """获取视频总时长（秒）"""
        try:
            result = subprocess.run([
                'ffprobe', '-v', 'error', '-show_entries',
                'format=duration', '-of',
                'default=noprint_wrappers=1:nokey=1', video_path
            ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
            return float(result.stdout.strip())
        except Exception as e:
            print(f"❌ 无法获取视频时长: {video_path}，错误: {e}")
            return None

    def split_in_half(self, video_path):
        """将单个视频平均切成两段"""
        duration = self.get_duration(video_path)
        if duration is None:
            return

        half = duration / 2
        filename, ext = os.path.splitext(os.path.basename(video_path))

        output1 = os.path.join(self.output_folder, f"{filename}_part1{ext}")
        output2 = os.path.join(self.output_folder, f"{filename}_part2{ext}")

        # 切第一段
        subprocess.run([
            'ffmpeg', '-y', '-i', video_path,
            '-t', str(half),
            '-c', 'copy', output1
        ], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)

        # 切第二段
        subprocess.run([
            'ffmpeg', '-y', '-i', video_path,
            '-ss', str(half),
            '-c', 'copy', output2
        ], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)

        print(f"✅ 已处理: {video_path} -> {output1}, {output2}")

    def process_all(self):
        """处理输入文件夹中所有支持的视频文件"""
        if not os.path.isdir(self.input_folder):
            print(f"❌ 输入文件夹不存在: {self.input_folder}")
            return

        for filename in os.listdir(self.input_folder):
            if filename.lower().endswith(self.supported_exts):
                video_path = os.path.join(self.input_folder, filename)
                self.split_in_half(video_path)


if __name__ == "__main__":
    input_folder = input("📂 请输入输入视频文件夹路径 x: ").strip()
    output_folder = input("📂 请输入输出文件夹 m: ").strip()

    splitter = VideoSplitter(input_folder, output_folder)
    splitter.process_all()
